package com.applcn.file.utils;

import cn.hutool.core.lang.Assert;
import com.applcn.file.apollo.FileConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 文件工具实现类切换开关
 */
@Component
@RequiredArgsConstructor
public class FileUtil {

    private Map<Integer, AbstractFileUtil> registerService = new ConcurrentHashMap<>(128);

    @Autowired
    private final List<AbstractFileUtil> abstractFileUtils;
    private final FileConfig fileConfig;

    @PostConstruct
    private void init() {
        abstractFileUtils.forEach(s -> {
            registerService.put(s.getIdentification(), s);
        });
    }

    /**
     * 获取开启的文件服务实现类
     *
     * @param code
     * @return
     */
    private AbstractFileUtil getFileUtil(int code) {
        AbstractFileUtil abstractFileUtil = registerService.get(code);
        Assert.notNull(abstractFileUtil, "未接入该平台文件服务");
        return abstractFileUtil;
    }

    /**
     * 获取预签名上传url
     *
     * @param fileName
     * @return
     */
    public String getCertification(String fileName) {
        return getFileUtil(fileConfig.getChoice()).getCertification(fileName);
    }

    /**
     * 获取文件url
     *
     * @param fileName
     * @return
     */
    public String getFileUrl(String fileName) {
        return getFileUtil(fileConfig.getChoice()).getFileUrl(fileName);
    }
}
